package com.miyake.client.profile;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.miyake.client.DoctorsUserService;
import com.miyake.client.DoctorsUserServiceAsync;
import com.miyake.client.tools.ShowDialog;
import com.miyake.client.tools.SmallButton;
import com.miyake.client.tools.UploadDialog;

public class FacePanel extends Composite {
	protected DoctorsUserServiceAsync service = DoctorsUserService.Util.getInstance();
	private Image image;
	public FacePanel(final UserProperty property, boolean me) {
		VerticalPanel panel = new VerticalPanel();
		initWidget(panel);
		image = new Image();
		if (property.getImageURL() != null) {
			image.setUrl(property.getImageURL());
		}
		else {
			image.setUrl("FaceSample.PNG");
		}
		image.setSize("167px", "169px");
		panel.add(image);
		if (me) {
			HorizontalPanel toolBar = new HorizontalPanel();
			panel.add(toolBar);
			toolBar.add(new SmallButton("Upload", new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					uploadImage(property);
				}
			}));
			toolBar.add(new SmallButton("Other images", new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					showFaceList(property);
				}
			}));
		}
	}

	protected void showFaceList(final UserProperty property) {
		new ShowDialog() {
			@Override
			protected void onOK(String text) {
				updateImage(property);
			}

			@Override
			protected DialogBox getDialogBox() {
				return new FaceListDialog(property.getKey());
			}
			
		};
	}

	protected void uploadImage(final UserProperty property) {
		new ShowDialog() {

			@Override
			protected void onOK(String text) {
				updateImage(property);
			}

			@Override
			protected DialogBox getDialogBox() {
				return new UploadDialog("faceKey," + property.getKey());
			}
			
		};
	}

	protected void updateImage(UserProperty property) {
		service.getUser(property.getKey(), new AsyncCallback<UserProperty>() {
			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(UserProperty result) {
				image.setUrl(result.getImageURL());
			}
		});
	}

}
